var params = app.getRequestParams();
var txt = params.type == 1 ? '收入':'支出';
var tcode = params.type == 1 ? 'QRK' : 'QCK';

$(function(){

    var rlabel = params.type == 1 ? '付款单位':'收款单位';
    var aplabel = params.type == 1 ? '收款金额':'付款金额';
    $('#relationId_label').html(rlabel);
    $('#accountPrice_label').html(aplabel);

    app.request({
        url:'resubject/select?type=1',
        success:function (resp) {
            initPage(resp.data);
        }
    });

});

function initPage(accountData) {
    $('#fixtable_zu').fixgrid({
        noscroll:true,
        width:950,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'操作',width:60,formatter:function () {
                        return gridOpt('#fixtable_zu');
                    }},
            ],[
                {field:'name',title:'<span class="red">*</span>'+txt+'科目',width:120,editor:'combobox',
                    getData:function(cell,callback){
                        return callback(accountData);
                    },comboboxData:function (that) {
                        return $(that).data();
                    }},
                {field:'price',title:'<span class="red">*</span>'+txt+'金额',width:120,editor:'decimal',editAfter:autoCalc},
                {field:'remarks',title:'备注',width:300,editor:'text'}
            ]
        ]
    });

    if(params.status==2){
        editable = false;
    }
    initButtons({service:'finOtherOrder',htmlName:'other',orderText:txt,codePrefix:tcode,orderType:0,gridId:'#fixtable_zu'});

    $('textarea[name="order.remarks"]').width($('#fixtable_zu').width()-14);
    $('#relationId').search({
        name:'order.relationId',
        click:function () {
            app.window(layer,{
                title:'付款单位选择',
                btn:[],
                area: ['800px', '600px'],
                content: '../../common/payer_list.html?index=-1&searchId=relationId'
            });
        }
    });

    $('#accountId').combobox({
        width:160,noDefault:true,
        url:'account/select',
        name:'order.accountId',
        valueField:'id',
        textField:'name'
    });
    $('#accountId').combobox('setValue',1,'现金账户');

    laydate.render({
        elem: '#order_date',value:app.getServerDate()
    });

    // 必须放在最后  所有代码要写在之前
    if(params.id){
        app.request({
            url:'finOtherOrder/getOrder',
            data:{id:params.id},
            success:function (resp) {
                initEdit(resp.data);
            }
        });
    }else{
        createRow('#fixtable_zu');createRow('#fixtable_zu');createRow('#fixtable_zu');
        $('#order_title').html('其他'+txt+'单');
    }
}

function autoCalc() {
    var totalMoney = '0';
    $('#fixtable_zu .ctx-right .vui-table-row .vui-table-cell[field="price"]').each(function () {

        var thisMoney = $(this).html();
        if( $.trim(thisMoney).length > 0 ){
            totalMoney = app.add(totalMoney,thisMoney);
        }
    });
    $('input[name="order.accountPrice"]').val(totalMoney);
}

//编辑初始化
function initEdit(data){
    var order = data.order;
    var accounts = data.accounts;

    init_edit_buttons(order,'#fixtable_zu');

    $('#order_title').html('编辑其他'+txt+'单【SK'+order.code+'】');
    $('#order_date').val(app.time2str(parseInt(order.date)));
    $('textarea[name="order.remarks"]').val(order.remarks);
    $('input[name="order.relationId_text"]').val(order.relationName);
    $('input[name="order.relationId"]').val(order.relationId);

    for (var i=0 ; i<accounts.length ; i++){
        var account = accounts[i];
        createRow('#fixtable_zu');
        var lastRowEle = $('#fixtable_zu .ctx-right .vui-table-row').last();
        lastRowEle.find('.vui-table-cell[field="name"]').html(account.resubjectName).data({value:account.resubjectId,text:account.resubjectName});;
        lastRowEle.find('.vui-table-cell[field="price"]').html(app.div(account.price,app.DIV));
        lastRowEle.find('.vui-table-cell[field="remarks"]').html(account.remarks);
    }

}

//保存
function saveAction(saveType,obj){
    var data = app.serializeForm();
    data['order.relationType'] = params.relationType;
    data['order.type'] = params.type;

    $.each(orderAccounts,function(i,row){
        for ( var n in row ){
            data["accounts["+i+"]."+n] = row[n];
            data["accounts["+i+"].ord"] = i;
        }
    });

    var url = 'finOtherOrder/insert';
    if(params.id){
        data['order.id'] = params.id;
        url = 'finOtherOrder/update';
    }

    data.saveType = saveType;
    doSave(url,data,saveType,obj);
}


//表单检查
var orderAccounts = [],accounts=[];
function checkForm(){

    var checkOptions = [
        {type:'input',name:'order.relationId_text',verify:[{type:'required'}]},
        {type:'input',name:'order.date',verify:[{type:'required'}]}
    ];

    if(app.checkForm(checkOptions)){

        var tipFlag = false;

        orderAccounts = [];
        $('#fixtable_zu .ctx-right .vui-table-row').each(function () {
            var detail = {};
            var subject = $(this).find('.vui-table-cell[field="name"]').data();

            if( subject.value ){
                //账户id
                detail.resubjectId = subject.value;

                var price = $(this).find('.vui-table-cell[field="price"]').html();
                // 金额
                if( $.trim(price).length == 0 ){
                    tipFlag = true;
                    app.msg(layer,'账户【'+subject.text+'】未填写收入金额',2);
                    return false;
                }
                detail.price = app.mul(price,app.DIV,0);

                // 备注
                detail.remarks = $(this).find('.vui-table-cell[field="remarks"]').html();
                orderAccounts[orderAccounts.length] = detail;
            }
        });

        if(orderAccounts.length > 0 && !tipFlag){
            return true;
        }else{
            if(!tipFlag){
                app.msg(layer,'至少填写一条收入记录',2);
                return false;
            }else{
                return false;
            }
        }
    }

    return false;
}